package com.yjh.server.controller.admin;

import com.yjh.common.utils.FileUploadUtil;
import com.yjh.pojo.vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

@RestController
@RequestMapping({"/admin/common","/mini/common"})
public class CommonController {

    @Value("${playbook.basePath}")
    private String basePath;

    @Autowired
    private FileUploadUtil fileUploadUtil;

    @GetMapping("/static/{fileName}")
    public ResponseEntity<byte[]> getImage(@PathVariable("fileName") String fileName) {
        InputStream inputStream = null;
        byte[] bytes = null;

        try {
            // 1. 拼接本地图片文件路径（basePath + 文件名）
            File imageFile = new File(basePath + fileName);

            // 2. 校验文件是否存在（避免404）
            if (!imageFile.exists()) {
                return new ResponseEntity<>(HttpStatus.NOT_FOUND); // 文件不存在返回404
            }

            // 3. 读取文件为字节数组（图片本质是二进制数据）
            inputStream = new FileInputStream(imageFile);
            bytes = new byte[inputStream.available()];
            inputStream.read(bytes);

            // 4. 设置响应头：告诉前端这是图片类型数据
            HttpHeaders headers = new HttpHeaders();
            // 根据文件后缀设置对应的Content-Type（如png/jpg）
            if (fileName.endsWith(".png")) {
                headers.setContentType(MediaType.IMAGE_PNG);
            } else if (fileName.endsWith(".jpg") || fileName.endsWith(".jpeg")) {
                headers.setContentType(MediaType.IMAGE_JPEG);
            } else if (fileName.endsWith(".gif")) {
                headers.setContentType(MediaType.IMAGE_GIF);
            }

            // 5. 返回图片字节数组 + 响应头 + 200状态码
            return new ResponseEntity<>(bytes, headers, HttpStatus.OK);

        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); // 读取失败返回500
        } finally {
            // 6. 关闭输入流（避免资源泄漏）
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @PostMapping("/uploadImgs")
    public R<String> uploadImgs(@RequestParam("readyList") List<MultipartFile> readyList)throws IOException{
        System.out.println(readyList);
        String newFilesUrl = fileUploadUtil.uploadFiles(readyList);

        return R.success(newFilesUrl);
    }

    @PostMapping("/uploadImg")
    public R<String> uploadImg(@RequestParam("img") MultipartFile img)throws IOException{
        System.out.println(img);
        String newFilesUrl = fileUploadUtil.uploadFile(img);

        return R.success(newFilesUrl);
    }
}
